package goerl

import (
	"errors"
	"fmt"
	"time"
)

type message struct {
	msg interface{}
}

//MailBox 并发节点信箱
type MailBox struct {
	messages    chan message
	receiveFunc func(interface{})
	node        *Node
}

//NewMailBox 创建并发节点信箱
func NewMailBox(queueSize int, recvFunc func(interface{})) *MailBox {
	return &MailBox{messages: make(chan message, queueSize), receiveFunc: recvFunc}
}

func (mailBox *MailBox) loop() {
	ticker := time.Tick(time.Millisecond * time.Duration(mailBox.node.UpdateSpeed))
	isExit := false
	lastTime := time.Now().UnixNano()
	for _ = range ticker {
		if mailBox.node.UpdateFunc != nil {
			mailBox.node.UpdateFunc(int((time.Now().UnixNano() - lastTime) / 1000000))
			lastTime = time.Now().UnixNano()
		}
		msgCount := len(mailBox.messages)
		if len(mailBox.messages) > 0 {
			for i := 0; i < msgCount; i++ {
				msg := <-mailBox.messages
				builtinCode := mailBox.builtinMail(msg)
				switch builtinCode {
				case 1:
					isExit = true
				case 0:
					if mailBox.receiveFunc != nil {
						mailBox.receiveFunc(msg.msg)
					}
				}
			}
		}
		if isExit {
			break
		}
	}
}
func (mailBox *MailBox) builtinMail(msg message) int {
	switch msg.msg.(type) {
	case []interface{}:
		tuple := msg.msg.([]interface{})
		if len(tuple) > 0 {
			switch tuple[0].(type) {
			case string:
				//内置退出消息
				if tuple[0].(string) == ":Exit" {
					return 1
				}
			}
		}
	}
	return 0
}

//Send 发送消息到并发节点的MailBox
func Send(toNode *Node, messageData interface{}) {
	toNode.mailBox.messages <- message{messageData}
}

//SendByName 根据注册的节点名称发送消息到并发节点的MailBox
func SendByName(name string, messageData interface{}) error {
	node := registerNodeMap[name]
	if node == nil {
		fmt.Println("不存在的节点名称" + name)
		return errors.New("不存在的节点名称" + name)
	}
	Send(node, messageData)
	return nil
}
